package com.qdxwx.manage.controller.category;

import com.qdxwx.common.annotation.Permissions;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.category.CategoryService;
import com.qdxwx.data.service.subject.SubjectService;
import com.qdxwx.manage.annotation.Log;
import com.qdxwx.manage.controller.BaseController;
import com.qdxwx.models.category.Category;
import com.qdxwx.models.enums.BusinessType;
import com.qdxwx.models.subject.Subject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 分类Controller
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Controller
@RequestMapping("/category")
public class CategoryEditController extends BaseController {
    private final String prefix = "category";

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SubjectService subjectService;

    /**
     * 新增分类
     */
    @GetMapping("/add.html")
    public String add(HttpServletRequest request, ModelMap mmap) {
        int parentId = TKConvert.toInteger(request.getParameter("parentId"));
        int channelId = TKConvert.toInteger(request.getParameter("channelId"));
        if (parentId > 0) {
            Category category = categoryService.get(parentId);
            mmap.put("category", category);
            channelId = category.getChannelId();
        }
        if (channelId < 1) {
            logger.error("未指定频道Id!");
            return error500;
        }
        mmap.put("channelId", channelId);
        mmap.put("subjects", subjectService.getList());
        return prefix + "/category-add";
    }

    /**
     * 新增保存分类
     */
    @Permissions("category:edit")
    @Log(title = "添加分类", businessType = BusinessType.INSERT)
    @PostMapping("/add.json")
    @ResponseBody
    public AjaxResult addSave(HttpServletRequest request) {
        List<String> nameList = new ArrayList<>();
        String categoryNames = request.getParameter("categoryName");
        if (categoryNames != null) {
            String[] names = categoryNames.split("\n");
            for (String name : names) {
                name = name.trim();
                if (name.length() < 1) {
                    continue;
                }
                if (!nameList.contains(name)) {
                    nameList.add(name);
                }
            }
        }
        if(nameList.size() < 1) return error("类别名称不能为空");
        int parentId = TKConvert.toInteger(request.getParameter("parentId"));
        int channelId = TKConvert.toInteger(request.getParameter("channelId"));
        int subjectId = TKConvert.toInteger(request.getParameter("subjectId"));
        if(parentId > 0){
            Category parentCategory = categoryService.get(parentId);
            if(parentCategory == null){
                return error("找不到指定上级分类。parentId="+parentId);
            }
            channelId = parentCategory.getChannelId();
            subjectId = parentCategory.getSubjectId();
        }
        if(channelId < 1){
            return error("频道id错误");
        }
        String subjectName = "无";
        if(subjectId > 1){
            Subject subject = subjectService.get(subjectId);
            if(subject == null){
                return error("找不到指定专业。subjectId="+subjectId);
            }
            subjectName = subject.getSubjectName();
        }

        int sort = TKConvert.toInteger(request.getParameter("sort"));
        int row = 0;
        for (int i = 0; i < nameList.size(); i++) {
            Category category = new Category();
            category.setParentId(parentId);
            category.setSubjectId(subjectId);
            category.setSubjectName(subjectName);
            category.setChannelId(channelId);
            category.setChildCount(0);
            category.setCategoryName(nameList.get(i));
            category.setSort(sort+i);
            row = categoryService.insert(category);
        }
        return toAjax(row);
    }

    /**
     * 修改分类
     */
    @GetMapping("/edit.html")
    public String edit(HttpServletRequest request , ModelMap mmap) {
        int categoryId = TKConvert.toInteger(request.getParameter("id"));
        Category category = categoryService.get(categoryId);
        if (category == null) return error500;
        if (category.getParentId() > 0) {
            Category parentCategory = categoryService.get(category.getParentId());
            mmap.put("parentCategory", parentCategory);
        }
        mmap.put("category", category);
        mmap.put("subjects", subjectService.getList());
        return prefix + "/category-edit";
    }

    /**
     * 修改保存分类
     */
    @Permissions("category:edit")
    @Log(title = "编辑分类", businessType = BusinessType.UPDATE)
    @PostMapping("/edit.json")
    @ResponseBody
    public AjaxResult editSave(HttpServletRequest request) {
        int categoryId = TKConvert.toInteger(request.getParameter("categoryId"));
        if (categoryId < 1) {
            return error("参数id错误，categoryId=" + categoryId);
        }
        Category category = categoryService.get(categoryId);
        if (category == null) {
            return error("找不到指定类别，categoryId=" + categoryId);
        }
        String categoryName = request.getParameter("categoryName");
        if (TKString.isEmpty(categoryName)) {
            return error("类别名称不能为空");
        }
        category.setCategoryName(categoryName);
        category.setSort(TKConvert.toInteger(request.getParameter("sort")));
        return toAjax(categoryService.update(category));
    }

    /**
     * 删除
     */
    @Permissions("category:remove")
    @Log(title = "删除分类", businessType = BusinessType.DELETE)
    @GetMapping("/remove.json")
    @ResponseBody
    public AjaxResult remove(HttpServletRequest request) {
        int categoryId = TKConvert.toInteger(request.getParameter("id"));
        return toAjax(categoryService.delete(categoryId));
    }
}
